package com.project.dao.activity;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.dtyunxi.util.DateUtil;
import com.google.common.collect.Lists;
import com.project.dao.BaseDao;
import com.project.entity.activity.Activity;

@Repository
public class ActivityDao extends BaseDao<Activity> {

	public List<Activity> getList(Activity activity){
		StringBuffer hql = new StringBuffer();
		hql.append(" select new Activity(a.id, a.name, a.activityStartDate, a.activityEndDate, a.registrationStartTime, a.registrationEndTime,  ")
			.append(" a.province, a.city, a.district, a.address, a.content, a.qrcodeUrl, a.coverPicUrl, a.publishStatus, ")
			.append(" a.createUser, a.createTime, a.updateUser, a.updateTime,COUNT(au.id) ,SUM(CASE au.auditStatus WHEN 'P' THEN 1 ELSE 0 END)  ) ")
			.append(" from Activity a left join ActivityUser au with a.id=au.activityId where 1=1 ");
		List<Object> list = Lists.newArrayList();
		if(activity.getActivityStartDate() != null){
			hql.append(" and DATE_FORMAT(a.activityStartDate,'%Y-%m-%d')  >= ? ");
			list.add(DateUtil.format(activity.getActivityStartDate(),"yyyy-MM-dd"));
		}
		if(activity.getActivityEndDate() != null){
			hql.append(" and DATE_FORMAT(a.activityEndDate,'%Y-%m-%d')  <= ? ");
			list.add(DateUtil.format(activity.getActivityEndDate(),"yyyy-MM-dd"));
		}
		if(activity.getRegistrationStartTime() != null){
			hql.append(" and DATE_FORMAT(a.registrationStartTime,'%Y-%m-%d')  >= ? ");
			list.add(DateUtil.format(activity.getRegistrationStartTime(),"yyyy-MM-dd"));
		}
		if(activity.getRegistrationEndTime() != null){
			hql.append(" and DATE_FORMAT(a.registrationEndTime,'%Y-%m-%d')  <= ? ");
			list.add(DateUtil.format(activity.getRegistrationEndTime(),"yyyy-MM-dd"));
		}
		
		hql.append(" group by a.id ");
		
		return this.find(hql.toString(), list.toArray());
	}
	
	public Activity getById(Activity activity){
		StringBuffer hql = new StringBuffer();
		hql.append(" select new Activity(a.id, a.name, a.activityStartDate, a.activityEndDate, a.registrationStartTime, a.registrationEndTime,  ")
			.append(" a.province, a.city, a.district, a.address, a.content, a.qrcodeUrl, a.coverPicUrl, a.publishStatus, ")
			.append(" a.createUser, a.createTime, a.updateUser, a.updateTime,COUNT(au.id) ,SUM(CASE au.auditStatus WHEN 'P' THEN 1 ELSE 0 END)  ) ")
			.append(" from Activity a left join ActivityUser au with a.id=au.activityId where 1=1 ");
		List<Object> list = Lists.newArrayList();
		if(activity.getId() != null){
			hql.append(" and a.id = ? ");
			list.add(activity.getId());
		}
		
		List<Activity> list2 = this.find(hql.toString(), list.toArray());
		if(list2!=null && list2.size()>0){
			return list2.get(0);
		}
		return  null;
	}
}
